package cn.edu.sysu.mail;

import java.sql.SQLException;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.sina.sae.mail.SaeMail;

import cn.edu.sysu.dto.IssueDto;
import cn.edu.sysu.dto.SolutionDto;
import cn.edu.sysu.dto.UserDto;
import cn.edu.sysu.service.UserService;

public enum MailUtil {

	INSTANCE;

	private static final String SMTP_HOST_NAME = "smtp.qq.com";
	private static final String SMTP_AUTH_USER = "zycbobby@sina.com";
	private static final String SMTP_AUTH_PWD = "zyc22216785";
	private static final String SMTP_PORT_NUM = "465";

	public String sendMail1(String[] fakeToList, String subject, String content) {

		InternetAddress[] realToList = new InternetAddress[fakeToList.length];

		String from = SMTP_AUTH_USER;
		Transport transport = null;
		// Set the host smtp address
		Properties properties = System.getProperties();
		properties.put("mail.smtp.host", SMTP_HOST_NAME);
		properties.put("mail.smtp.user", SMTP_AUTH_USER);
		properties.put("mail.smtp.port", SMTP_PORT_NUM);
		properties.put("mail.smtp.socketFactory.port", SMTP_PORT_NUM);
		properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		properties.put("mail.smtp.auth", "true");
		properties.put("mail.smtp.debug", "true");
		properties.put("mail.smtp.starttls.enable", "true");
		properties.put("javax.net.ssl.SSLSocketFactory", "false");

		Authenticator auth = new SMTPAuthenticator();
		Session session = Session.getDefaultInstance(properties, auth);

		MimeMessage message = new MimeMessage(session);

		try {
			message.setFrom(new InternetAddress(from));

			for (int i = 0; i < fakeToList.length; i++) {
				realToList[i] = new InternetAddress(fakeToList[i]);
			}

			message.setRecipients(Message.RecipientType.TO, realToList);
			message.setSubject(subject);
			message.setContent(content, "text/plain");
			// For HTML-Email
			// message.setContent(content, "text/html");

			transport = session.getTransport("smtp");
			transport.connect(SMTP_HOST_NAME, Integer.valueOf(SMTP_PORT_NUM).intValue(), SMTP_AUTH_USER, SMTP_AUTH_PWD);

			transport.sendMessage(message, message.getAllRecipients());
			return "Message sent successflly...";
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return "fail1";
		} catch (MessagingException e) {
			System.out.println(e.getMessage());
			return e.toString();
		} finally {
			try {
				transport.close();
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

	public String sendMail(String[] fakeToList, String subject, String content){
		SaeMail mail = new SaeMail();
		mail.setCc(new String[]{"zuo.yc@qq.com"});
		mail.quickSend(SMTP_AUTH_USER, fakeToList,
				subject, content, SMTP_AUTH_USER, SMTP_AUTH_PWD);
		if(!mail.getErrno().equals("0")){
			mail.clean();
			mail.quickSend("zuoyuchu@qq.com", fakeToList,
					subject, content, "zuoyuchu@qq.com", SMTP_AUTH_PWD);

		}
		return mail.getErrno()+" msg:"+mail.getErrmsg();
	}

	public static final String MAIL_SUBJECT_HEAD = "[AlgorithmWeekly]";
	public static final String SOLUTION_HEAD = "[Solution]";
	public static final String Issue_HEAD = "[Issue]";
	public static final String ADMIN_ADDRESS = "zuo_y@worksap.co.jp";
	public static final String MAIL_TAIL = "\n If you dont want to receive this kind of mail, please ignore it";

	public void SendSolutionPostMail(UserDto user, SolutionDto sd) throws SQLException, InterruptedException,
			ExecutionException {
		String subject = MAIL_SUBJECT_HEAD
				+ SOLUTION_HEAD
				+ user.getUser_name()
				+ " has published a solution for problem "
				+ sd.getProblem_id()
				+ "!";
		String content = "Hi all, \n please check in http://1.cwsalgorithm.sinaapp.com/1/cwsalgorithm/vm/problem.vm?problem_id="
				+ sd.getProblem_id()
				+ MAIL_TAIL;

		UserService us = new UserService();
		List<UserDto> users = us.getMailingList();
		String[] fakeToList = new String[users.size()];
		for (int i = 0; i < fakeToList.length; i++) {
			fakeToList[i] = users.get(i).getEmail();
		}

		ExecutorService e = Executors.newFixedThreadPool(2);
		Future<String> f1 = e.submit(new MailThread(fakeToList, subject, content));

		System.out.println(f1.get());
	}

	public void SendIssuePostMail(UserDto user, IssueDto issue) throws SQLException, InterruptedException,
			ExecutionException {
		String subject = MAIL_SUBJECT_HEAD
				+ Issue_HEAD
				+ user.getUser_name()
				+ " has published an issue for problem "
				+ issue.getProblem_id()
				+ "!";
		String content = "Hi all, \n please check in http://1.cwsalgorithm.sinaapp.com/1/cwsalgorithm/vm/issuelist.vm?problem_id="
				+ issue.getProblem_id()
				+ MAIL_TAIL;

		UserService us = new UserService();
		List<UserDto> users = us.getMailingList();
		String[] fakeToList = new String[users.size()];
		for (int i = 0; i < fakeToList.length; i++) {
			fakeToList[i] = users.get(i).getEmail();
		}

		ExecutorService e = Executors.newFixedThreadPool(2);
		Future<String> f1 = e.submit(new MailThread(fakeToList, subject, content));
		System.out.println(f1.get());
	}

	private class SMTPAuthenticator extends Authenticator {
		@Override
		public PasswordAuthentication getPasswordAuthentication() {
			String username = SMTP_AUTH_USER;
			String password = SMTP_AUTH_PWD;

			return new PasswordAuthentication(username, password);
		}
	}
}
